import { View, MovableArea, MovableView, Text } from '@tarojs/components';
import { useState } from 'react';
import './index.scss';

interface GoodsSlideProps {
  // 商品标题
  title: string;
  // 商品价格
  price: string;
  // 侧滑操作按钮文本
  actionText?: string;
  // 操作按钮点击事件
  onActionClick?: () => void;
  // 最大滑动距离
  maxSlideDistance?: number;
}

const GoodsSlide = ({
                      title,
                      price,
                      actionText = '删除',
                      onActionClick,
                      maxSlideDistance = 80
                    }: GoodsSlideProps) => {
  // 控制滑动位置的状态
  const [x, setX] = useState(0);

  // 处理滑动事件
  const handleChange = (event) => {
    const currentX = event.detail.x;

    // 限制滑动范围
    if (currentX > maxSlideDistance) {
      setX(maxSlideDistance);
    } else if (currentX < 0) {
      setX(0);
    } else {
      setX(currentX);
    }
  };

  // 点击操作按钮
  const handleActionClick = () => {
    // 点击后复位
    setX(0);
    // 触发回调
    if (onActionClick) {
      onActionClick();
    }
  };

  return (
    <View className="goods-slide-container">
      <MovableArea className="movable-area">
        <MovableView
          className="movable-view"
          direction="horizontal"
          x={x}
          onChange={handleChange}
          // 释放时如果滑动距离超过一半则完全展开，否则收起
          onTouchEnd={() => {
            if (x > maxSlideDistance / 2) {
              setX(maxSlideDistance);
            } else {
              setX(0);
            }
          }}
        >
          {/* 商品信息区域 */}
          <View className="goods-info">
            <Text className="goods-title">{title}</Text>
            <Text className="goods-price">{price}</Text>
          </View>

          {/* 侧滑操作区域 */}
          <View
            className="slide-action"
            onClick={handleActionClick}
          >
            <Text>{actionText}</Text>
          </View>
        </MovableView>
      </MovableArea>
    </View>
  );
};

export default GoodsSlide;
